package com.gf.user.service.impl;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.gf.base.type.Activity;
import com.gf.base.type.BloodType;
import com.gf.base.type.LicenseState;
import com.gf.base.type.Sex;
import com.gf.common.constant.Constants;
import com.gf.common.util.CertCodeHelper;
import com.gf.common.util.SmsHelper;
import com.gf.common.util.WebHelper;
import com.gf.fund.service.FundService;
import com.gf.user.dao.UserBaseDao;
import com.gf.user.dao.UserDao;
import com.gf.user.model.User;
import com.gf.user.service.IdolFanService;
import com.gf.user.service.UserService;

@Transactional
@Service("userService")
public class UserServiceImpl implements UserService {

	@Autowired
	private UserDao userDao;

	@Autowired
	private UserBaseDao userBaseDao;

	@Autowired
	private FundService fundService;

	@Autowired
	private IdolFanService idolFanService;

	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	@Override
	public void initUser(long userId) {
		// 初始化帐号金额
		fundService.initFund(userId);
		idolFanService.initIdolFan(userId);
	}

	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	@Override
	public void changeProtrait(long id, String protraitUrl) {
		userDao.updateProtrait(id, protraitUrl);
	}

	@Override
	public String getProtrait(long id) {
		return userDao.queryProtrait(id);
	}

	@Override
	public HashMap<String, List<String>> getAllNicknameAndUid() {
		List<Map<String, Object>> nickuid = userDao
				.queryAllNicknameAndUidForAutocomplete();

		List<String> nicknames = new ArrayList<String>();
		List<String> uids = new ArrayList<String>();

		for (Map<String, Object> map : nickuid) {
			nicknames.add((String) map.get("nickname"));// 与数据库对应
			uids.add("" + map.get("id"));// 与数据库对应
		}

		HashMap<String, List<String>> suggestionDatas = new HashMap<String, List<String>>();
		suggestionDatas.put("nickname", nicknames);
		suggestionDatas.put("uid", uids);

		return suggestionDatas;
	}

	@Override
	public User getUserById(long id) {
		return userBaseDao.queryUserById(id);
	}

	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	@Override
	public boolean setupUpdate(Long userId, Sex sex, BloodType bloodType,
			String income, String experience) {

		return userDao.updateSetup(userId, sex, bloodType, income, experience);
	}

	/**
	 * 绑定手机 发送手机验证码
	 */
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	@Override
	public long sendMobileCode(long userId, String smsMob) {
		String code = CertCodeHelper.getMobileCert();
		String text = "尊敬的客户：您绑定该手机号码的验证码为:" + code + "。有效时间为12个小时。请及时绑定。-- 医务系统";

		int result = SmsHelper.sendSingle(smsMob, text);
		// 发送成功后写到数据库
		if (result > 0) {
			return userDao.insertMobileCode(userId, smsMob, code);
		}
		return -1;
	}

	/**
	 * 验证绑定手机的验证码是否正确
	 */
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	@Override
	public boolean verifyMobileCode(long userId, String code) {
		Map<String, Object> mobile = userDao.queryMobileCode(userId, code);
		Date date = (Date) mobile.get("createtime");
		if (date == null) {
			return false;
		}

		long time = date.getTime();
		long now = System.currentTimeMillis();
		if (now - time > 12 * 3600 * 1000) {
			return false;
		}
		BigInteger idBig = (BigInteger) mobile.get("id");
		long id = idBig.longValue();
		userDao.updateMobileActivity(id, Activity.DELETED);

		// 手机号码
		String number = (String) mobile.get("number");
		userDao.updateUserMobile(userId, number);

		// 更新session
		User user = WebHelper.getSessionUser();
		WebHelper.removeSessionAttribute(Constants.SESSION_USER);
		user.setCellphone(number);
		WebHelper.setSessionAttribute(Constants.SESSION_USER, user);

		return true;
	}

	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	@Override
	public void uploadLicense(long userId, String newPath) {
		userDao.insertLicense(userId, newPath, LicenseState.CHECKING);
	}

	@Override
	public void changeLoginUserInfo(long userId) {
		String ip = WebHelper.getClientIp(null);
		
		userDao.updateLoginUserInfo(userId,ip);
	}

}
